package com.soul.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

/**
 * AES/ECB/PKCS7Padding 加解密
 *
 *    <dependency>
 *        <groupId>org.bouncycastle</groupId>
 *        <artifactId>bcprov-jdk15on</artifactId>
 *        <version>1.64</version>
 *    </dependency>
 */
public class AESUtils {


    private static final String SECRET = "AES";
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static void main(String[] args) throws Exception {
        String str = "{\"nsrsbh\":\"12440100G341146862\",\"jylsh\":\"6bdcdc0b-4ed2-4cc9-989e-8420122a5295\",\"authId\":\"9112011632857960XM\"}";
        System.out.println("字符串：" + str);
        String encryptStr = AESUtils.aes256ECBPkcs7PaddingEncrypt(str, "Syu0JdkYvyuu9930");
        System.out.println("加密后字符串：" + encryptStr);
        String decryptStr = AESUtils.aes256ECBPkcs7PaddingDecrypt(encryptStr, "Syu0JdkYvyuu9930");
        System.out.println("解密后字符串：" + decryptStr);
    }


    /**
     * AES加密ECB模式PKCS7Padding填充方式
     *
     * @param str 字符串
     * @param key 密钥
     * @return 加密字符串
     * @throws Exception 异常信息
     */
    public static String aes256ECBPkcs7PaddingEncrypt(String str, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(doFinal));
    }

    /**
     * AES解密ECB模式PKCS7Padding填充方式
     *
     * @param str 字符串
     * @param key 密钥
     * @return 解密字符串
     * @throws Exception 异常信息
     */
    public static String aes256ECBPkcs7PaddingDecrypt(String str, String key) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, SECRET));
        byte[] doFinal = cipher.doFinal(Base64.getDecoder().decode(str));
        return new String(doFinal);
    }
}